# -*- coding:utf-8 -*-

from django.contrib.auth.decorators import login_required
from django.contrib.auth import login as login_function, logout as logout_function, authenticate
from django.contrib.auth.models import User
from django.contrib.auth.views import logout_then_login
from django.shortcuts import render_to_response, redirect
from django.http import HttpResponseRedirect
from django.template.context import RequestContext
from aventon.traveling.forms import VehiculoForm, UserForm, ViajeroForm, ViajeForm
from aventon.traveling.models import Viajero, Barrio, Viaje
from datetime import  date

BARRIOS = Barrio.objects.all()


@login_required
def nuevo_viaje(request):
    user = User.objects.get(pk=request.user.id)
    if request.method == 'POST':
        viaje_form = ViajeForm(request.POST)
        if viaje_form.is_valid():
            viaje = viaje_form.save()
            viaje.save()
            return redirect('/traveling/home/')
    else:
        viaje_form = ViajeForm()
    return render_to_response('traveling/nuevo.html', {'title': 'Nuevo Viaje',
                                                       'user': user,
                                                       'form': viaje_form},
        context_instance=RequestContext(request))


@login_required
def nuevo_vehiculo(request):
    user = User.objects.get(pk=request.user.id)
    if request.method == 'POST':
        vehiculo_form = VehiculoForm(request.POST)
        if vehiculo_form.is_valid():
            vehiculo = vehiculo_form.save()
            vehiculo.save()
            return redirect('/traveling/home/')
    else:
        vehiculo_form = VehiculoForm()
    return render_to_response('traveling/nuevo.html', {'title': 'Nuevo Vehiculo',
                                                       'user': user,
                                                       'form': vehiculo_form},
        context_instance=RequestContext(request))


@login_required
def inicio(request):
    user = User.objects.get(pk=request.user.id)
    return render_to_response('traveling/inicio.html', {'title': 'Home',
                                                        'barrios': BARRIOS,
                                                        'user': user},
        context_instance=RequestContext(request))


def registro(request):
    user = None
    if request.user.is_authenticated():
        logout_function(request)
    if request.method == 'POST':
        user_form = UserForm(request.POST)
        if user_form.is_valid():
            new_user = user_form.save()
            new_user.is_active = True
            new_user.username = new_user.email
            new_user.set_password(user_form.instance.password)
            new_user.save()
            viajero = Viajero()
            viajero.usuario = new_user
            viajero.save()
            auth_user = authenticate(username=new_user.email,
                password=request.POST['password'])
            login_function(request, auth_user)
            return redirect('/traveling/perfil/')
    else:
        user_form = UserForm()
    return render_to_response('traveling/registro.html', {'title': 'Registro',
                                                          'user': user,
                                                          'barrios': BARRIOS,
                                                          'user_form': user_form},
        context_instance=RequestContext(request))


@login_required
def perfil(request):
    user = User.objects.get(pk=request.user.id)
    viajero = Viajero.objects.get(usuario=user)
    msj = ''
    if request.method == 'POST':
        viajero_form = ViajeroForm(request.POST, instance=viajero)
        user_form = UserForm(request.POST, instance=user)
        if viajero_form.is_valid() and user_form.is_valid():
            viajero = viajero_form.save()
            viajero.save()
            user = user_form.save()
            user.save()
            msj = u'Sus datos fueron guardados'
    else:
        viajero_form = ViajeroForm(instance=viajero)
        user_form = UserForm(instance=user)
    return render_to_response('traveling/perfil.html', {'title': 'Perfil',
                                                        'user': user,
                                                        'viajero': viajero,
                                                        'msj': msj,
                                                        'barrios': BARRIOS,
                                                        'user_form': user_form,
                                                        'viajero_form': viajero_form},
        context_instance=RequestContext(request))


def ingresar(request):
    try:
        next_url = request.REQUEST['next']
    except:
        next_url = '/traveling/'
    user = None
    if request.user.is_authenticated():
        return HttpResponseRedirect(next_url)
    msg = u''
    if request.method == 'POST':
        if request.POST['email'] and request.POST['password']:
            user = authenticate(username=request.POST['email'], password=request.POST['password'])
            if user is not None:
                if user.is_active:
                    login_function(request, user)
                    return HttpResponseRedirect(next_url)
                else:
                    msg = u'Su cuenta no está activa'
            else:
                msg = u'e-mail y/o clave no válidos'
    return render_to_response('traveling/ingresar.html', {'title': u'Ingresar',
                                                          'next': next_url,
                                                          'barrios': BARRIOS,
                                                          'user': user,
                                                          'msg': msg},
        context_instance=RequestContext(request))


def salir(request):
    return logout_then_login(request)


def buscar(request, desde=None, hasta=None, ano=None, mes=None, dia=None, oferta=None):
    if request.user.is_authenticated():
        user = User.objects.get(pk=request.user.id)
    else:
        user = None
    try:
        oferta = False if not oferta == 'oferta' else True
        barrio_desde = Barrio.objects.get(pk=desde)
        barrio_hasta = Barrio.objects.get(pk=hasta)
        puntos_desde = barrio_desde.puntos.all()
        puntos_hasta = barrio_hasta.puntos.all()
        fecha = date(int(ano), int(mes), int(dia))
        #mes_siguiente = (fecha + timedelta(365 / 12))
        viajes = Viaje.objects.filter(desde__in=puntos_desde, hasta__in=puntos_hasta, oferta=oferta)#,
        #fecha_hora__lte=mes_siguiente, fecha_hora__gte=fecha)
        if viajes:
            return render_to_response('traveling/buscar.html', {'title': u'Viajes',
                                                                'barrios': BARRIOS,
                                                                'user': user,
                                                                'viajes': viajes},
                context_instance=RequestContext(request))
        else:
            return render_to_response('traveling/buscar.html', {'title': u'Viajes',
                                                                'user': user,
                                                                'barrios': BARRIOS,
                                                                'msj': u'La busqueda no produjo resultados'},
                context_instance=RequestContext(request))
    except:
        return render_to_response('traveling/buscar.html', {'title': u'Viajes',
                                                            'user': user,
                                                            'barrios': BARRIOS,
                                                            'msj': u'ERROR: La busqueda no produjo resultados'},
            context_instance=RequestContext(request))
